package com.yinuo.starter.config;

import com.yinuo.starter.util.JDBCUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

@Component
@Order(Ordered.LOWEST_PRECEDENCE - 2)
public class TransactionalInit implements CommandLineRunner {

    @Autowired
    private JDBCUtil jdbcUtil;

    private static final String TRANS_TABLE_NAME = "%TRANS%_DATA";

    private static final String TRANS_CREATE_SQL = "CREATE TABLE If Not Exists `%TRANS%_DATA` (\n" +
            "  `id` varchar(50) NOT NULL COMMENT 'ID',\n" +
            "  `topic_name` varchar(50) NOT NULL,\n" +
            "  `tag_name` varchar(50),\n" +
            "  `keys` varchar(50),\n" +
            "  `value` varchar(50),\n" +
            "  `type` tinyint(1) NOT NULL,\n" +
            "  `create_time` timestamp NULL DEFAULT NULL,\n" +
            "  `modify_time` timestamp NULL DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`)\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='事务表';";

    @Override
    public void run(String... args) throws Exception {
        tableHandler();
    }

    public void tableHandler() throws SQLException {
        if(!jdbcUtil.isTableExist(TRANS_TABLE_NAME)){
            jdbcUtil.createTable(TRANS_TABLE_NAME, TRANS_CREATE_SQL);
        }
    }
}
